<template>
  <div>
    <input type="file" @change="handleFileUpload" class="fileInput" ref="fileInput" />
    <img :src="avatarUrl" alt="头像" v-if="avatarUrl" class="avatarImage" @click="tologin" />
    <div @click="openFileDialog" class="load">点击上传</div>

    
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';


// 存储上传后的图片URL
const avatarUrl = ref(localStorage.getItem('avatarUrl') || '');

const fileInput = ref(null);

// 文件输入框的点击事件
const openFileDialog = () => {
  fileInput.value.click();
};

// 处理文件上传的函数
const handleFileUpload = async () => {
  const file = fileInput.value.files[0];
  if (file) {
    const formData = new FormData();
    formData.append('avatar', file);

    try {
      // 链接后端接口，获取后端接口地址
      const response = await axios.post('/api/upload-avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      if (response.data.status === '200') {
        avatarUrl.value = response.data.avatarUrl;
        localStorage.setItem('avatarUrl', response.data.avatarUrl);
      }
    } catch (error) {
      console.error('头像上传失败:', error);
    }
  }
}




</script>




<style scoped lang="scss">

img{
  height: 100px;
  width: 100px;
}

</style>

